package cn.tedu._03vehice.controller;

import cn.tedu._03vehice.base.response.JsonResult;
import cn.tedu._03vehice.base.response.StatusCode;
import cn.tedu._03vehice.mapper.UserMapper;
import cn.tedu._03vehice.pojo.dto.UserLoginParam;
import cn.tedu._03vehice.pojo.dto.UserRegParam;
import cn.tedu._03vehice.pojo.entity.User;
import cn.tedu._03vehice.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RequestMapping("v1/user/")
@RestController
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("reg")
    public JsonResult add(@Validated @RequestBody UserRegParam userRegParam){
        log.debug("userRegParam = " + userRegParam);
        String username = userRegParam.getUsername();
        int select = userMapper.selectByUsername(username);
        if(select > 0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("user = " + user);
        int i = userMapper.insertUser(user);
        if(i>0){
            return JsonResult.ok();
        }else{
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 20)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession httpSession){
        log.debug("userLoginParam = " + userLoginParam);
        UserVO userVO = userMapper.selectByUsernamePassword(userLoginParam);
        if(userVO!=null){
            httpSession.setAttribute("user", userVO);
            return JsonResult.ok("欢迎" + userVO + "回来");
        }else{
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
    }
    @GetMapping("currentUser")
    @ApiOperation("获取当前用户功能")
    @ApiOperationSupport(order=30)
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");

        return JsonResult.ok(userVO);
    }

    @GetMapping("logout")
    @ApiOperation("退出登录功能")
    @ApiOperationSupport(order = 40)
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
